<template>
  <div class="reg">
    <div class="regMain">
      <div class="regTop clearfix">
        <h2 class="fl">快速注册</h2>
        <p class="fr">
          已有账号？
          <router-link to="login">登录</router-link>
        </p>
      </div>

      <form class="reg_form">
        <el-form :label-position="labelPosition"
                 ref="ruleForm"
                 :rules="rules"
                 label-width="125px"
                 :model="ruleForm" style="position:relative;">
          <span style='color:#F56C6C;font-size:14px;position:absolute;top:71px;left:33px;'>*</span>
          <el-form-item label="企业账号："
                        prop="userAccount">
            <el-input v-model="ruleForm.userAccount"></el-input>
          </el-form-item>

          <el-form-item label="企业名称："
                        v-if='flag3==0'
                        prop="companyName" class="qiye">
            <el-autocomplete
              v-model="ruleForm.companyName"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入企业名称"
              @blur="handleSelect({value:ruleForm.companyName})"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="企业名称："
                        v-if='flag3==1'
                        prop="companyName" class="qiye qiye1">
            <el-autocomplete
              v-model="ruleForm.companyName"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入企业名称"
              @blur="handleSelect({value:ruleForm.companyName})"
              @select="handleSelect"
            ></el-autocomplete>
            <p style='color:#F56C6C;font-size:12px;position:absolute;top:32px;' v-if='flag3'>请输入企业名称</p>
          </el-form-item>
          <el-form-item label="企业名称："
                        v-if='flag3==2'
                        prop="companyName" class="qiye qiye2">
            <el-autocomplete
              v-model="ruleForm.companyName"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入企业名称"
              @blur="handleSelect({value:ruleForm.companyName})"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="社会信用代码："
                        prop="socialCreditCode">
            <el-input v-model="ruleForm.socialCreditCode"></el-input>
          </el-form-item>
          <el-form-item label="有无应急预案：" prop="isExist">
            <el-radio-group v-model="ruleForm.isExist">
              <el-radio label="有"></el-radio>
              <el-radio label='无'></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="主要负责人："
                        prop="legalPerson">
            <el-input v-model="ruleForm.legalPerson"></el-input>
          </el-form-item>

          <el-form-item label="应急值班电话："
                        prop="contactInfo">
            <el-input v-model="ruleForm.contactInfo"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱 :"
                        prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="所属行业 :"
                        prop="businessId">
            <el-select v-model="ruleForm.businessId"
                       @change="selectChildren(0,ruleForm.businessId)">
              <el-option v-for="(item,index) in businessList1"
                         :label="item.name"
                         :key="index"
                         :value="item.id"></el-option>
            </el-select>
            <el-select v-model="businessId2"
                       @change="selectChildren(1,businessId2)">
              <el-option v-for="(item,index) in businessList2"
                         :label="item.name"
                         :key="index"
                         :value="item.id"></el-option>
            </el-select>
            <el-select v-model="businessId" @change="selectGet">
              <el-option v-for="(item,index) in businessList3"
                         :label="item.name"
                         :key="index"
                         :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属地区 :" style="margin-bottom: 0" required>
            <el-row>
              <el-col :span="6">
                <el-form-item
                  prop="regionId">
                  <el-select v-model="ruleForm.regionId"
                             @change="changeRegion(0,ruleForm.regionId)">
                    <el-option v-for="(item,index) in regionList1"
                               :label="item.name"
                               :key="index"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  prop="regionId2">
                  <el-select v-model="ruleForm.regionId2"
                             @change="changeRegion(1,ruleForm.regionId2)">
                    <el-option v-for="(item,index) in regionList2"
                               :label="item.name"
                               :key="index"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  prop="regionId3">
                  <el-select v-model="ruleForm.regionId3">
                    <el-option v-for="(item,index) in regionList3"
                               :label="item.name"
                               :key="index"
                               :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="密码："
                        prop="userPassword">
            <el-input v-model="ruleForm.userPassword"
                      type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码："
                        prop="userPassword2">
            <el-input v-model="ruleForm.userPassword2"
                      type="password"></el-input>
          </el-form-item>
          <el-form-item label="联系人："
                        prop="contacter">
            <el-input v-model="ruleForm.contacter"></el-input>
          </el-form-item>
          <el-form-item label="姓名："
                        prop="userName">
            <el-input v-model="ruleForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="手机号："
                        prop="mobileNo">
            <el-input v-model="ruleForm.mobileNo"></el-input>
          </el-form-item>
          <el-form-item label="手机验证码："
                        prop="smsCode"
                        style="width:480px;">
            <el-col :span="15">
              <el-input v-model="ruleForm.smsCode"></el-input>
            </el-col>
            <el-col class="fr"
                    :span="8">
              <a class="getYzm"
                 @click="getCode"
                 v-show="codeFlag">点击获取</a>
              <a class="getYzm"
                 id="smsCode"
                 v-show="!codeFlag">点击获取</a>
            </el-col>
          </el-form-item>
        </el-form>
        <div class="regBtn_box">
          <input type="button"
                 value="注册"
                 @click="submitForm('ruleForm')">
        </div>
      </form>
    </div>
    <p class="reg_footer">Copy Right © Bossien All Rights Reserved 武汉博晟安全技术股份有限公司 版权所有</p>
    <el-dialog title="系统提示"
               :visible.sync="systemNote"
               width="40%">
      <span class="regTcNote">
        <img src="../../../static/images/warn_icon.png">注册信息已提交，在一个工作日之内审核通过，即可使用。谢谢！
      </span>
      <span slot="footer"
            class="dialog-footer">
        <input @click="goPath"
               type="button"
               value="确 认"
               class="tcSubmit">
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import config from "../../config.js";

  export default {
    data() {

      var checkPsd = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入密码"));
        } else {
          const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error("请输入8-16位密码,包括大小写及数字"));
          }
        }
      };
      var checkCode = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入社会信用代码"));
        } else {
          if (/^[a-zA-Z0-9]{18}$/.test(value)) {
            callback();
          } else {
            return callback(new Error("社会信用代码为18位"));
          }
        }
      };
      var checkUserAccount = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入企业账号"));
        } else {
          const reg = /^[\w]{6,32}$/;
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error("请输入6-32位,只能是字母、数字和下划线"));
          }
        }
      };
      var checkAccount = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入企业名称"));
        }
      };
      var checkPsd2 = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入密码"));
        } else {
          if (value == this.ruleForm.userPassword) {
            callback();
          } else {
            return callback(new Error("密码不一致"));
          }

        }
      };
      var checkPhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("手机号不能为空"));
        } else {
          const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error("请输入正确的手机号"));
          }
        }
      };
      var checkTelephone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("手机号不能为空"));
        } else {
          const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
          const reg1 = /^0\d{2,3}-?\d{7,8}$/;
          if (reg.test(value) || reg1.test(value)) {
            callback();
          } else {
            return callback(new Error("请输入正确的手机号"));
          }
        }
      };
      const isSelect = (rule, value, callback) => {
        if (this.regionList3 != null && this.regionList3.length != 0 && !value) {
          return callback(new Error("请选择区"));
        } else {
          callback();
        }
      };
      return {
        options: [],
        value: [],
        list: [],
        flag3: 0,
        loading: false,
        labelPosition: "right",
        businessList: [],
        codeFlag: true,
        time: null,
        businessId: '',
        businessList1: [],
        businessId2: '',
        businessList2: [],
        businessList3: [],
        regionId: '',
        regionId2: '',
        regionId3: '',
        regionList: [],
        regionList1: [],
        regionList2: [],
        regionList3: [],
        businessName1: '',
        businessName2: '',
        businessName3: '',
        ruleForm: {
          businessId: "",
          companyName: "",
          contactInfo: "",
          email: "",
          legalPerson: "",
          contacter: "",
          mobileNo: "",
          smsCode: "",
          socialCreditCode: "",
          userAccount: "",
          userName: "",
          userPassword: "",
          userPassword2: '',
          isExist: '无',
          regionId: '',
          regionId2: '',
          regionId3: '',
          businessName1: '',
          businessName2: '',
          businessName3: '',
        },
        systemNote: false,
        rules: {
          userName: [{required: true, message: "请输入姓名", trigger: "blur"}],
          email: [
            {required: true, message: "请输入电子邮箱", trigger: "blur"},
            {
              required: true,
              type: "email",
              message: "请输入正确的电子邮箱",
              trigger: "blur"
            }
          ],
          businessId: [
            {required: true, message: "请输入所属行业", trigger: "blur"}
          ],
          userPassword: [
            {required: true, message: "请输入密码", trigger: "blur"},
            {
              required: true,
              validator: checkPsd,
              message: "请输入8-16位密码,必须包含大小写字母及数字",
              trigger: "blur"
            }
          ],
          userPassword2: [
            {required: true, message: "请输入密码", trigger: "blur"},
            {
              required: true,
              validator: checkPsd2,
              message: "密码不一致",
              trigger: "blur"
            }
          ],
          socialCreditCode: [
            {required: true, message: "请输入社会信用代码", trigger: "blur"},
            {
              required: true,
              validator: checkCode,
              message: "社会信用代码为18位",
              trigger: "blur"
            }
          ],
          isExist: [
            {required: true, message: '请选择有无应急预案', trigger: 'change'}
          ],
          legalPerson: [
            {required: true, message: "请输入主要负责人", trigger: "blur"}
          ],
          contacter: [
            {required: true, message: "请输入联系人", trigger: "blur"}
          ],
          contactInfo: [
            {required: true, message: "请输入应急值班电话", trigger: "blur"},
            {
              required: true,
              validator: checkTelephone,
              message: "请输入电话或者手机号",
              trigger: "blur"
            }
          ],
          userAccount: [
            {required: true, message: "请输入账号", trigger: "blur"},
            {
              required: true,
              validator: checkUserAccount,
              message: "请输入6-32位,只能是字母、数字和下划线",
              trigger: "blur"
            }
          ],
          mobileNo: [
            {required: true, message: "请输入手机号", trigger: "blur"},
            {
              required: true,
              validator: checkPhone,
              message: "请输入正确的手机号",
              trigger: "blur"
            }
          ],
          smsCode: [
            {required: true, message: "请输入手机验证码", trigger: "blur"}
          ],
          regionId: [
            {required: true, message: "请选择省份", trigger: 'blur'},
          ],
          regionId2: [
            {required: true, message: "请选择市", trigger: 'blur'},
          ],
          regionId3: [
            {required: true, validator: isSelect, trigger: 'blur'},
          ],
        },
        restaurants: [],
        state: '',
        timeout: null
      };
    },

    mounted() {
      this.getBusiness();
      this.loadAll();
      this.getRegionInfo();
    },
    methods: {
      loadAll() {
        this.getAllCompany()
      },
      querySearchAsync(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 2000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.match(queryString));
        };
      },
      handleSelect(item) {
        if (item.value == '') {
          this.flag3 = 1
        } else {
          this.flag3 = 2
        }
      },
      goPath() {
        this.systemNote = false
        this.$router.push('login')
      },
      getAllCompany() {
        this.$axios
          .post(config.baseUrl + "emergency/v1.0/query/companys", {
            companyName: '',
          })
          .then(res => {
            if (res.data.meta.success) {
              let result = []
              res.data.data.map((item) => {
                result.push({value: item.varName})
              })

              this.restaurants = result
            } else {
              this.$message.warning(res.data.meta.message);
            }
          })
          .catch(response => {
            console.log(response);
          });
      },
      selectChildren(n, id) {
        console.log(n, id)
        var list = []
        this.businessList.map((item, index) => {
          if (item.pid == id) {
            list.push(item)
          }
        })
        if (n == 0) {
          this.businessId2 = ''
          this.businessId = ''
          var arr = []
          list.map(item => {
            if (item.level == 2) {
              arr.push(item)
            }
          })
          // list.map(item=>{
          //     if(item.id == 5 || item.id == 12 || item.id == 34 || item.id == 59 || item.id == 68 || item.id == 67){
          //         arr.push(item)
          //     }
          // })
          let obj = {};
          obj = this.businessList1.find((item) => {//这里的userList就是上面遍历的数据源
            return item.id === id;//筛选出匹配数据
          });
          console.log(obj.name);//我这边的name就是对应label的
          this.businessName1 = obj.name
          this.businessList2 = arr
        } else {
          this.businessId = ''
          var arr = []
          list.map(item => {
            if (item.level == 3) {
              arr.push(item)
            }
          })
          // list.map(item=>{
          //     if(item.id == 18 || item.id == 19 || item.id == 22 || item.id == 6 || item.id == 7 || item.id == 14 || item.id == 13 || item.id == 62){
          //         arr.push(item)
          //     }
          // })
          let obj = {};
          obj = this.businessList2.find((item) => {//这里的userList就是上面遍历的数据源
            return item.id === id;//筛选出匹配数据
          });
          console.log(obj.name);//我这边的name就是对应label的
          this.businessName2 = obj.name
          this.businessList3 = arr
        }
      },
      getBusiness() {
        this.$axios
          .post(config.baseUrl + "emergency/v1.0/business/list", {
            pageIndex: 1,
            pageSize: 1000,
            searchType: "2"
          })
          .then(res => {
            if (res.data.meta.success) {
              this.businessList = res.data.data.records;
              res.data.data.records.map(item => {
                if (item.level == 1) {
                  this.businessList1.push(item)
                }
              })
              //选择展示的行业
              //  var arr=[]
              //  this.businessList1.map(item=>{
              //      if(item.id == 2 || item.id == 3 || item.id == 37 || item.id == 42){
              //          arr.push(item)
              //      }
              //  })
              //  this.businessList1=arr
            } else {
              this.$message.warning(res.data.meta.message);
            }
          })
          .catch(response => {
            console.log(response);
          });
      },
      getCode() {
        this.codeFlag = false;
        var reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
        if (reg.test(this.ruleForm.mobileNo)) {
          var t = 30;
          this.time = setInterval(() => {
            t--;
            if (t != 0) {
              document.getElementById("smsCode").innerHTML = t + "s";
            } else {
              t = 0;
              clearInterval(this.time);
              this.codeFlag = true;
            }
          }, 1000);
          this.$axios
            .post(config.baseUrl + "emergency/v1.0/sms/verifyCode", {
              mobileNo: this.ruleForm.mobileNo
            })
            .then(res => {
              if (res.data.meta.success) {
                this.$message.success(res.data.data.verifySuccess);
              } else {
                this.$message.warning(res.data.meta.message);
              }
            })
            .catch(response => {
              console.log(response);
            });
        } else {
          this.$message.warning("请输入正确的手机号");
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
           let fbusinessId=this.ruleForm.businessId;
           let tbusinessId='';
            if (this.businessId != '') {
             // this.ruleForm.businessId = this.businessId
              tbusinessId= this.businessId
            } else {
              if (this.businessId2 != '') {
               // this.ruleForm.businessId = this.businessId2
                tbusinessId= this.businessId2
              }
            }
             if(fbusinessId=='2'&&tbusinessId==''){
               this.$message.warning("请选择二级行业")
               return
             }
            let params = {
              fbusinessId:fbusinessId,
             // businessId: this.ruleForm.businessId,
              businessId: tbusinessId?tbusinessId:fbusinessId,
              areaId: this.ruleForm.regionId3,
              cityId: this.ruleForm.regionId2,
              provinceId: this.ruleForm.regionId,
              companyName: this.ruleForm.companyName,
              contactInfo: this.ruleForm.contactInfo,
              email: this.ruleForm.email,
              legalPerson: this.ruleForm.legalPerson,
              contacter: this.ruleForm.contacter,
              mobileNo: this.ruleForm.mobileNo,
              smsCode: this.ruleForm.smsCode,
              socialCreditCode: this.ruleForm.socialCreditCode,
              userAccount: this.ruleForm.userAccount,
              userName: this.ruleForm.userName,
              userPassword: this.$md5(this.ruleForm.userPassword),
              isExist: this.ruleForm.isExist == '有' ? '1' : '2',
              specialBusinessName: this.businessName2 + ',' + this.businessName3
            }
           //console.log(11 + JSON.stringify(params))
            this.$axios
              .post(config.baseUrl + "emergency/v1.0/register", params)
              .then(res => {
                if (res.data.meta.success) {
                  this.$refs[formName].resetFields();
                  this.systemNote = true
                } else {
                  this.$message.warning(res.data.meta.message)
                }
              })
              .catch(response => {
                console.log(response);
              });
          } else {
            this.$message.warning("请完善信息后再注册！");
            return false;
          }
        });
      },
      getRegionInfo() {
        this.$axios
          .post(config.baseUrl + "emergency/v1.0/region/list", {
            pageIndex: 1,
            pageSize: 5000,
            searchType: "2"
          })
          .then(res => {
            if (res.data.meta.success) {
              this.regionList = res.data.data.records;
              res.data.data.records.map(item => {
                if (item.type == 1) {
                  this.regionList1.push(item)
                }
              })

            } else {
              this.$message.warning(res.data.meta.message);
            }
          })
          .catch(response => {
            console.log(response);
          });
      },
      changeRegion(n, id) {
        console.log(n, id)
        var list = []
        this.regionList.map((item, index) => {
          if (item.parentId == id) {
            list.push(item)
          }
        })
        if (n == 0) {
          this.ruleForm.regionId2 = ''
          this.ruleForm.regionId3 = ''
          var arr = []
          list.map(item => {
            if (item.type == 2) {
              arr.push(item)
            }
          })
          this.regionList2 = arr
        } else {
          this.ruleForm.regionId3 = ''
          var arr = []
          list.map(item => {
            if (item.type == 3) {
              arr.push(item)
            }
          })
          this.regionList3 = arr
        }
      },
      selectGet(id) {//这个vId也就是value值
        let obj = {};
        obj = this.businessList3.find((item) => {//这里的businessList3就是上面遍历的数据源
          return item.id === id;//筛选出匹配数据
        });
        console.log(obj.name);//我这边的name就是对应label的
        this.businessName3 = obj.name
      }
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less' scoped>
  .reg {
    height: 100%;
    min-height: 1300px;
    width: 100%;
    background: url("../../../static/images/loginBg.jpg") no-repeat;
    background-size: 100% 100%;
    position: relative;
    .regMain {
      background: #fff;
      width: 1100px;
      position: absolute;
      left: 50%;
      margin-left: -550px;
      top: 48%;
      margin-top: -450px;
      padding-bottom: 60px;
      .regTop {
        padding: 10px 42px 0 35px;
        margin-bottom: 30px;
        h2 {
          font-size: 16px;
          font-weight: bold;
        }
        p {
          a {
            text-decoration: underline;
            color: #4080ff;
          }
          a:hover {
            opacity: 0.8;
            text-decoration: underline;
          }
        }
      }
      .reg_form {
        .el-form-item {
          margin-bottom: 20px;
        }
        margin-left: 290px;
        .getYzm {
          width: 100%;
          display: block;
          height: 40px;
          border-radius: 8px;
          border: 1px solid #dcdfe6;
          color: #4080ff;
          text-align: center;
          cursor: pointer;
          margin-top: 1px;
        }
        .getYzm:hover {
          opacity: 0.8;
        }
        .regBtn_box {
          padding-top: 15px;
          > input {
            margin-left: 125px;
            width: 355px;
            height: 40px;
            color: #fff;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            background: #4080ff;
         /*   background: linear-gradient(left, #6fb2ff 0%, #095fff 100%);
            background: -ms-linear-gradient(left, #6fb2ff 0%, #095fff 100%);
            background: -moz-linear-gradient(left, #6fb2ff 0%, #095fff 100%);*/
          }
          > input:hover {
            opacity: 0.8;
          }
        }
      }
    }
    .reg_footer {
      position: absolute;
      bottom: 3%;
      font-size: 12px;
      width: 100%;
      text-align: center;
      color: #888;
    }
    .regTcNote {
      img {
        margin-right: 15px;
      }
    }
    .tcSubmit {
      height: 36px;
      width: 135px;
      color: #fff;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      background: #4080ff;
    /*  background: linear-gradient(left, #6fb2ff 0%, #095fff 100%);*/
    }
    .tcSubmit:hover {
      opacity: 0.8;
    }
  }

  .el-col-6 {
    width: 24%;
  }
</style>
